import './css/index.less';

const imgs = [
    "https://gitee.com/top_super/cloud-img/raw/master/1.jpg",
    "https://gitee.com/top_super/cloud-img/raw/master/2.jpg",
    "https://gitee.com/top_super/cloud-img/raw/master/3.jpg",
    "https://gitee.com/top_super/cloud-img/raw/master/4.jpg",
    "https://gitee.com/top_super/cloud-img/raw/master/5.jpg",
]

const loadingImg = 'https://gitee.com/top_super/cloud-img/raw/master/loading.gif';

const imgDom = document.querySelector("img");

const preLoad = preLoadFn(imgDom, imgs);

imgDom.addEventListener('click', preLoad, false);

preLoad();

function preLoadFn (imgDom, urls) {
    let i = 0;
    return () => {
        i = i < urls.length ? i : 0;

        loadImg(urls[i])
            .then(imgLoadSuccess(imgDom, urls[i]))
            .catch(imgLoadFail(imgDom, urls[i]));

        i++;
        i = i < urls.length ? i : 0;

        loadImg(urls[i]).then(() => console.log("预加载图片成功"));
    }
};

function loadImg(url) {
    return new Promise((resolve, reject) => {
        const tImg = new Image();

        tImg.src = url;
        tImg.onload = () => {
            resolve(tImg);
        }
        tImg.onerror = () => {
            reject(tImg);
        }
    });
}

function imgLoadSuccess(img) {
    return (tImg) => {
        img.src = tImg.src;
    }
}

function imgLoadFail(img) {
    let i = 0;
    return (tImg) => {
        if (navigator.onLine) {
            if(i < 3) {
                tImg.src = tImg.src;
                i++;
            } else {
                img.src = '';
            }
        } else {
            setTimeout(() => {
                tImg.src = tImg.src;
            }, 500);
        }
    }
}